package es.wtestgen.util;

import javax.transaction.Transaction;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.sql.InFragment;

public class HibernateUtil2 {

	private static final SessionFactory sessionFactory;
	
	private static final ThreadLocal threadSession = new ThreadLocal();
	
	private static final ThreadLocal threadTransaction = new ThreadLocal();
	
	private static final Configuration cfg = new Configuration();
	
	static{
		//inicializamos el sessionFactory
		sessionFactory = cfg.buildSessionFactory(); 
	}
	
	public static Session getSession(){
		Session s = (Session)threadSession.get();

		//abrimos una nueva session si este hilo no la tiene todavia
		try{
			if(s == null){
				s = sessionFactory.openSession();
				threadSession.set(s);
			}
		}catch(HibernateException ex){
			System.err.println("_______Error en getSession_______");
			ex.printStackTrace();
		}
		return s;
	}
	
	
	public static void closeSession(){
		try{
			Session s = (Session)threadSession.get();
			threadSession.set(s);
		}catch(HibernateException ex){
			System.err.println("_______Error en closeSession_______");
			ex.printStackTrace();
		}
	}
	
	
	public static void beginTransaction(){
		Transaction tx = (Transaction)threadTransaction.get();		
		try{
			if(tx == null){
				tx = (Transaction)getSession().beginTransaction();
				threadTransaction.set(tx);
			}
		}catch(HibernateException ex){
			System.err.println("_______Error en beginTransaction_______");
			ex.printStackTrace();		}
	}
}
